package cn.Alibaba.basic.controller;


import cn.Alibaba.basic.util.FastDfsUtils;
import cn.Alibaba.basic.util.JsonResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    @PostMapping
    public JsonResult upload(@RequestPart(required = true, value="file") MultipartFile file){

        try {

            //获取原始文件名
            String originalFilename = file.getOriginalFilename();
            // 截取以点结尾的文件名
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
            // 做文件上传操作
            String filename = FastDfsUtils.upload(file.getBytes(), extName);
            // 对前端要做一个响应
            return JsonResult.me().setResultObj(filename);

        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setResultObj("上传失败");
        }

    }

    @DeleteMapping
    public JsonResult delete(@RequestParam(required = true ,value = "path") String path){

        try {
            String pathTmp = path.substring(1);
            String group = pathTmp.substring(0, pathTmp.indexOf("/")); // group1
            String namePath = pathTmp.substring(pathTmp.indexOf("/") + 1);
            // 删除操作
            FastDfsUtils.delete(group,namePath);

            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();

            return JsonResult.me().setResultObj("删除失败");
        }


    }
}
